<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\command;

use think\console\Input;
use think\console\Output;
use think\db\exception\DbException;
use think\facade\Db;

class DownMemberLevel extends BaseCommand
{

    protected function configure()
    {
        // 指令配置
        $this->setName('down_level')
            ->setDescription('会员等级到期,关闭');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->setDb($input, $output);
    }

    protected function executeAction(Input $input, Output $output)
    {
        $userList = Db::table('jiecheng_user')
            ->where('status', 1)
            ->whereNull('delete_time')
            ->where('level', '>', 0)
            ->whereTime('level_time', '<', date('Y-m-d H:i:s', strtotime('-1 year')))
            ->select();
        if ($userList) {
            foreach ($userList as $k => $v) {
                Db::startTrans();
                try {
                    $record = [
                        'mall_id' => $v->mall_id,
                        'user_id' => $v->id,
                        'base_in' => 'admin',
                        'source_type' => 4,
                        'source' => '会员到期,清0',
                        'old_level' => $v->level,
                        'new_level' => 0,
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s'),
                    ];
                    Db::table('jiecheng_membership_record')->insert($record);
                    Db::table('jiecheng_user')->where(['id' => $v->id])->update(['level' => 0, 'level_time' => date('Y-m-d H:i:s')]);
                    Db::commit();
                } catch (DbException $e) {
                    Db::rollback();
                }
            }
        }
        // 指令输出
        $output->writeln('会员清零成功');
    }

}
